<template>
	<div class="page-container">
		<h1>随机选择工具</h1>
		<el-form :model="form" label-position="top">
			<el-form-item label="随机组">
				<el-input v-model.trim="form.options" placeholder="请输入随机组，用逗号（,）分隔"></el-input>
			</el-form-item>
			<el-form-item label="选择数量">
				<el-input v-model.number="form.count" type="number" :min="1" placeholder="请输入选择数量"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="generateRandomSelection">生成随机选择</el-button>
			</el-form-item>
		</el-form>
		<el-form label-position="top">
			<el-form-item label="输出">
				<el-input v-model="randomSelection.join(', ')" readonly></el-input>
			</el-form-item>
		</el-form>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					options: '',
					count: 1,
				},
				randomSelection: [],
			};
		},
		methods: {
			generateRandomSelection() {
				const {
					options,
					count
				} = this.form;
				let optionsArr = options.split(',').map((str) => str.trim());
				// 过滤掉空字符串
				optionsArr = optionsArr.filter((option) => option !== '');
				const numOptions = optionsArr.length;
				if (numOptions === 0) {
					this.$message.error('随机组不能为空！');
					return;
				}
				if (count > numOptions) {
					this.$message.error(`选择数量不能大于随机组数量（${numOptions}）！`);
					return;
				}
				let selectedOptions = [];
				while (selectedOptions.length < count) {
					const randomIndex = Math.floor(Math.random() * numOptions);
					const randomOption = optionsArr[randomIndex];
					if (!selectedOptions.includes(randomOption)) {
						selectedOptions.push(randomOption);
					}
				}
				this.randomSelection = selectedOptions;
			},
		},
	};
</script>


